﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Net;
using System.Configuration;

namespace WebNext.UI.Utils.Mailing
{
	public class GmailNotifier : IEmailNotifier
	{
		private string fromAddress;
		private string fromDisplayName;
		private string fromPassword; 
		private string defaultToAddress;

		public GmailNotifier()
		{
			this.fromAddress = ConfigurationManager.AppSettings["EmailFromAddress"];
			this.fromDisplayName = ConfigurationManager.AppSettings["EmailFromDisplayName"];
			this.fromPassword = ConfigurationManager.AppSettings["EmailFromPassword"];
			this.defaultToAddress = ConfigurationManager.AppSettings["EmailToAddress"];
		}

		public void Notify(string to, string subject, string body)
		{
			MailAddress fromMailAddress = new MailAddress(this.fromAddress, this.fromDisplayName);
			MailAddress toMailAddress = new MailAddress(to);

			SmtpClient smtpClient = new SmtpClient
			{
				Host = "smtp.gmail.com",
				Port = 587,
				EnableSsl = true,
				DeliveryMethod = SmtpDeliveryMethod.Network,
				UseDefaultCredentials = false,
				Credentials = new NetworkCredential(fromMailAddress.Address, fromPassword)
			};

			MailMessage mailMessage = new MailMessage(fromMailAddress, toMailAddress)
			{
				Subject = subject,
				Body = body
			};

			using (smtpClient)
			{
				using (mailMessage)
				{
					smtpClient.Send(mailMessage);
				}
			}
		}

		public void Notify(string subject, string body)
		{
			this.Notify(this.defaultToAddress, subject, body);
		}

	}
}